【问题标题】:SQL: How to return two more row data from table `property`? [duplicate]SQL:如何从表“property”返回两行数据? [复制]
【发布时间】:2011-11-12 19:44:45
【问题描述】:

可能重复:
SQL - how to SELECT multiple tables and JOIN multiple rows from the same column?

我有三个 MySQL 表 - languagecategoryproperty

/*
table `language`
`WHERE language.url='link'`*/
id   | url
-----+-----
111  | link

/*
table `category`
`SELECT category.id, category.order`*/
id   | order  | group | type | location
-----+--------+-------+------+---------
111  | 3      | a42   | a81  | a63

/*
table `property`
`LEFT JOIN properties ON properties.id = category.group`*/
id  | status
----+-------
a42 | public
a81 | update
a63 | states

和 SQL

SELECT category.id, category.order, language.url, property.status AS `group`
FROM category
LEFT JOIN language
USING ( id )
LEFT JOIN property ON property.id = category.group
WHERE language.url='link'
LIMIT 1

返回

id  | order | url   | group
----+-------+-------+-------
111 | 3     | link  | public

SQL:如何从表property 中再返回两行数据,结果将是:

id  | order | url   | group  | type   | location
----+-------+-------+--------+--------+---------
111 | 3     | link  | public | update | states

【问题讨论】:

  • 你应该真正编辑你现有的问题,而不是问另一个问题,或者删除一个。
  • 没关系,但您可能无法获得所需的选票。如果您标记问题并在文本框中说明您打开了两个问题并想关闭它,版主可以这样做。

标签: mysql sql select join


【解决方案1】:

您还需要 2 个 LEFT JOINs

SELECT category.id, category.order, language.url
   , g.status AS `group`, t.status AS `type`, l.status AS `location`
FROM category
LEFT JOIN language
USING ( id )
LEFT JOIN property AS g ON category.group = g.id
LEFT JOIN property AS t ON category.type = t.id 
LEFT JOIN property AS l ON category.location = l.id 
WHERE language.url='link'
LIMIT 1

【讨论】:

  • phpMyAdmin 返回错误 #1054 - '字段列表'中的未知列 'g.status'
  • 您在我的回答中运行整个查询时收到了该错误?您是否可以将别名 g 添加到当前的 LEFT JOIN property 并将您的选择更改为 g.status 而不是 property.status
  • 我在 MySQL 5.5.16 上尝试过你的建议,但它仍然返回相同的错误 ERROR 1054 (42S22): Unknown column 'g.status' in 'field list'
  • 谢谢!它确实有效,我的 mysql 数据库之前错过了一些列。为了获得更好的性能 - 如果没有这样的需要,请不要使用 LEFTRIGHT
  • 我很高兴它对你有用。我使用了LEFT JOINs,因为它们在您的原始帖子中,我不确定每个类别的每个状态是否总是有一个值。我在INNER JOINs 上同意你的观点,但在适当的情况下。
猜你喜欢
  • 2016-05-07
  • 1970-01-01
  • 2016-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
  • 1970-01-01
相关资源
最近更新 更多