【问题标题】:How to look for a value in SQL filtered in the same query如何在同一查询中过滤的 SQL 中查找值
【发布时间】:2018-04-06 20:36:49
【问题描述】:

我会尝试通过例子来解释我需要什么。

我有两张桌子

TableA
ID  Name
1   John
2   Mary

TableB
ID  IDNAME
1   1#ab
2   1#a
3   2#ac

所以我需要从 TableB 中选择每个 id 并使用 tableB.IDNAME 中的 subtring_index 函数从 tableA 中获取名称。

Example
SELECT `ID`, SUBSTRING_INDEX(`IDNAME`, '#', 1) AS 'NAME' FROM `tableB`

这将返回以下结果,但我想从 tableA 中获取对应的名称,而不是 NAME 列中的 id 值

TEMP Table
ID  NAME
1   1         <= John
2   1         <= John
3   2         <= Mary

希望你能帮助我

【问题讨论】:

    标签: mysql sql database substring


    【解决方案1】:

    你可以这样做:

    select b.*, a.name
    from b left join
         a
         on substring_index(b.idname, '#', 1) = a.id;
    

    您不需要substring_index()。另一种方法是使用like

    select b.*, a.name
    from b left join
         a
         on b.idname like concat(a.id, '#%');
    

    【讨论】:

    • 谢谢它真的有帮助,我根据我的需要和它的工作进行调整。另一个问题..如果我需要将这种链接指向另一个表,我该怎么做?
    猜你喜欢
    • 2014-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    相关资源
    最近更新 更多