使用基于表名的php / mysql分离数据

时间:2013-06-05 22:19:32

标签: php mysql

我想要做的是查询我的数据库“sc2”并搜索3个表以获取某些信息。

我有3张桌子

===
Matches
====
matchid
matchname
casterid
eventid

=== 
Casters
===
casterid
casteralias
casterurl

===
Events 
===
eventid
eventname

我正在使用的当前SQL语句在某种程度上起作用:

$sql = "
SELECT m.title AS matchTitle, c.casteralias matchCaster, m.dateadded matchDate, 
comp.eventname FROM matches m
LEFT JOIN 
casters AS c
ON 
c.casterid = m.casterid
LEFT OUTER JOIN
competitions AS comp
ON m.eventid = comp.id
WHERE m.title LIKE '%".$search."%'
OR 
c.casteralias LIKE '%".$search."%'
OR 
comp.eventname LIKE '%".$search."%'
ORDER BY
m.dateadded
DESC";

它提取了必要的信息,但我想在结果集中区分原始表,因此我可以根据找到的结果来自哪个表来操作结果。

matchTitle  matchCaster matchDate   eventname
Hero vs Revival HuskyStarcraft  2013-06-05 15:54:05 \N
Idra vs Stephano    HuskyStarcraft  2013-05-30 13:28:05 \N
Stephano vs BabyKnight  HuskyStarcraft  2013-05-29 14:31:46 WCS Europe
Trimaster vs Destiny    HuskyStarcraft  2013-05-28 18:26:45 \N
RorO vs Innovation  HuskyStarcraft  2013-05-27 22:04:28 \N
Psy vs Camara   HuskyStarcraft  2013-05-26 02:13:10 \N
Minigun vs Maker    HuskyStarcraft  2013-05-23 20:05:00 \N

结果似乎很好..我只需要确定一种方法来区分搜索结果的实际显示,这取决于首先搜索的内容。因此,如果用户搜索施法者,而不是获取最近的匹配信息,他们将获得施法者的缩略图以及来自该特定施法者的最近投射。

我希望自己清楚明白,并提前感谢您提出的任何建议。 :)

1 个答案:

答案 0 :(得分:0)

有点凌乱,但这就是你所追求的

Select * from (
SELECT "Matches" as Source, m.title AS matchTitle, 
c.casteralias as matchCaster, m.dateadded as matchDate, comp.eventname 
FROM matches m
LEFT JOIN casters AS c ON c.casterid = m.casterid
LEFT OUTER JOIN competitions AS comp ON m.eventid = comp.id
WHERE m.title LIKE '%".$search."%'
Union
SELECT "Caster", m.title, 
c.casteralias,m.dateadded, comp.eventname 
FROM matches m
LEFT JOIN casters AS c ON c.casterid = m.casterid
LEFT OUTER JOIN competitions AS comp ON m.eventid = comp.id
WHERE c.casteralias LIKE '%".$search."%'
Union
SELECT "Event", m.title, 
c.casteralias,m.dateadded, comp.eventname 
FROM matches m
LEFT JOIN casters AS c ON c.casterid = m.casterid
LEFT OUTER JOIN competitions AS comp ON m.eventid = comp.id
WHERE comp.eventname LIKE '%".$search."%') allLikes

ORDER BY matchDate DESC