3

我是内部连接的新手,我似乎无法弄清楚这里出了什么问题。我希望返回表“事件”中的所有行。这是我的表:

+----+---------+----------+    +----+---------+
| ID |  name   | venue_id |    | ID | name    |
+----+---------+----------+    +----+---------+
| 1  | Hub dub | 2        |    | 2  | hub dub |
| 2  | Test 2  | 2        |    +----+---------+
| 3  | Test 3  | 2        |
| 4  | Test 4  | 2        |
+----+---------+----------+

这是查询:

SELECT DISTINCT a.*, b.name AS venue a 
FROM events b 
INNER JOIN venues ON a.venue_id = b.id 
WHERE a.name LIKE '%hub%' OR b.name LIKE '%hub%'

出于某种原因,在我更复杂的版本中,仅返回事件 ID#1。

4

6 回答 6

1

语法有点不对劲。别名 ( a) 需要在表之后(在列别名之后有它)。

SELECT DISTINCT a.*, b.name AS venue 
FROM events b 
INNER JOIN venues a ON a.venue_id = b.id 
WHERE a.name LIKE '%hub%' OR b.name LIKE '%hub%'
于 2012-12-24T17:14:30.427 回答
1

是错字吗?

SELECT DISTINCT a.*, b.name AS venue a
-------------------------------------^

应该是这样的:

SELECT DISTINCT a.*, b.name AS venue 
FROM events b 
INNER JOIN venues a ON a.venue_id = b.id 
WHERE a.name LIKE '%hub%' OR b.name LIKE '%hub%'

它被称为别名。它应该始终在表侧,之后FROM

于 2012-12-24T17:15:18.223 回答
0

那样做

         SELECT DISTINCT a.*, b.name AS venue 
         FROM events b 
         INNER JOIN venues a ON a.venue_id = b.id 
         WHERE a.name LIKE '%hub%' OR b.name LIKE '%hub%'
于 2012-12-24T17:17:58.497 回答
0

这是你想要的吗?

SELECT DISTINCT a.*, b.name AS venue a FROM events b LEFT JOIN venues ON a.venue_id = b.id and b.name LIKE '%hub%'

于 2012-12-24T17:18:02.477 回答
0

结果是正确的,你已经通过venue_id和id连接了两个表,结果是表中的所有行都带有表事件的列名,之后你过滤了两个表上存在的列名,字符串包含%hub%,结果只是第一行。

PS你错过了桌子场地的标签。

于 2012-12-24T17:20:00.307 回答
0

我认为你想要的是左连接表 A 和 B。

SELECT a.*, b.name AS venue FROM events b 
   LEFT JOIN venues a ON a.venue_id = b.id
   WHERE a.name LIKE '%hub%' OR b.name LIKE '%hub%'

http://www.sqlfiddle.com/#!2/a2581/1/0

于 2012-12-24T17:22:13.040 回答