【问题标题】:Select column which have same name from subquery从子查询中选择具有相同名称的列
【发布时间】:2019-07-11 06:06:58
【问题描述】:

两个表具有相同的名称id,现在我想通过使用子查询的where子句从子查询中获取两个id列

这是具有两列 p.id 和 s.id 的查询

select name,price,total,user_id,id,id from(
SELECT p.name,p.price,s.user_id,s.id,p.id FROM products p,shoping_cart 
s where p.id=s.product_id
) z where z.user_id=11

【问题讨论】:

  • 使用别名,例如's.id as sid',然后你基本上重命名了列,你可以在外部查询中使用别名。
  • 您好,为子查询中的列指定别名,如下所示:select ...,id_s,id_p from ( select .., s.id as ID_S, p.id as ID_P from ..) ..

标签: mysql


【解决方案1】:

首先,您可以尝试使用别名来表示这两列。

你的查询中没有理由需要使用子查询,你可以尝试直接select它。

我会使用join 语法而不是, 逗号来连接两个表,因为, 的意思是CROSS JOIN 这是一种旧样式。

SELECT 
    p.name,
    p.price,
    s.user_id,
    s.id 'sid',
    p.id 'pid'
FROM products p JOIN shoping_cart s  on p.id=s.product_id
WHERE s.user_id = 11

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 2019-11-11
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多