1

我有三张桌子:乐队、演出和场地。我希望能够按乐队名称、乐队家乡和场地名称进行搜索。这是我的表格的大致概念:

乐队

ID    |    NAME      |    LOCATION
------|--------------|------------
1     | Spinal Tap   | New York, NY
2     | Jimi Hendrix | Woodstock, PA

演出

ID    |    VENUE_ID    |    START_TIME    |    BAND_ID
------|----------------|------------------|--------------
1     |    1           |    1371171600    |    1
2     |    2           |    1371171600    |    1
3     |    1           |    1371171600    |    2
4     |    2           |    1371171600    |    1

场地

ID    |    NAME
------|---------------------
1     |  Madison Square Garden
2     |  Jefferson Round Garden

因此,按乐队名称和位置搜索很容易。就像是:

  SELECT id,name,location 
    FROM bands 
   WHERE name LIKE '%$search_string%' OR location LIKE '%$search_string%' 
ORDER BY name

如果我想包括按场地名称搜索的可能性怎么办?这是我可怕的拙劣尝试:

    SELECT bands.id,bands.name,bands.location,venues.name 
      FROM bands 
     WHERE name LIKE '%$search_string%' OR location LIKE '%$search_string%' 
INNER JOIN gigs 
        ON bands.id=gigs.band_id 
INNER JOIN venues 
        ON gigs.venue_id=venues.id 
     WHERE start_time>'$now' 
  ORDER BY bands.name

我显然对这整个内部连接的事情很陌生......

4

2 回答 2

2

你很亲近;只需要一些调整:

SELECT
  bands.id,
  bands.name,
  bands.location,
  venues.name
FROM bands
INNER JOIN gigs ON bands.id = gigs.band_id
INNER JOIN venues ON gigs.venue_id = venues.id
WHERE start_time>'$now'
  AND (
     bands.name LIKE '%whatever%' OR
     bands.location LIKE '%whatever%' OR
     venues.name LIKE '%whatever%'
      )

中的括号WHERE很重要,因为OR它的优先级低于AND

于 2013-06-19T21:26:49.043 回答
1

你的 somne​​thing 有问题JOIN,你应该先通过表并将它们和 useWHERE子句连接起来。如您所见,我使用ALIAS了表,并且使用了列名前面的那些来让数据库了解表的来源。

SELECT a.id,a.name,a.location,c.name 
FROM bands a
INNER JOIN gigs b
ON a.id=b.band_id 
INNER JOIN venues c
ON b.venue_id=c.id 
WHERE (a.name LIKE '%$search_string%' OR a.location LIKE '%$search_string%' OR C.name LIKE '%search_string%')
AND b.start_time>'$now' 
ORDER BY a.name
于 2013-06-19T21:24:49.537 回答