开发者

Problems with MySQL OR clause

开发者 https://www.devze.com 2022-12-22 20:45 出处:网络
I have a problem with AND and OR clause in SQL. Here is my query: SELECT `act1`.`name`, `act1`.`surname`,

I have a problem with AND and OR clause in SQL. Here is my query:

SELECT  
    `act1`.`name`,
    `act1`.`surname`,
    `act2`.`name`,
    `act2`.`surname`,
    `act3`.`name`,
    `act3`.`surname`
FROM 
    `videos`,
    `actors` AS act1,
    `actors` AS act2,
    `actors` AS act3
WHERE 
    `videos`.`ident` = 'somethi开发者_Python百科ng' 
  AND 
    (
        `act1`.`id` = `videos`.`id_actor1`
      OR 
        `act2`.`id` = `videos`.`id_actor2`
      OR
        `act3`.`id` = `videos`.`id_actor3`
    )

It returns me all variations of {name, surname}, but I want the name and surname of first exactly, second and third, if they exist.


Sounds like you need LEFT JOINS.

SELECT  
`act1`.`name`,
`act1`.`surname`,
`act2`.`name`,
`act2`.`surname`,
`act3`.`name`,
`act3`.`surname`
FROM  `videos`
LEFT JOIN `actors` AS act1 ON ( `act1`.`id` = `videos`.`id_actor1` )
LEFT JOIN `actors` AS act2 ON ( `act2`.`id` = `videos`.`id_actor2` )
LEFT JOIN `actors` AS act3 ON ( `act3`.`id` = `videos`.`id_actor3` )
WHERE `videos`.`ident` = 'somethink' 

The syntax you use is deprecated anyway, use JOIN and LEFT JOIN instead of listing table names in the FROM clause.


Your question sounds as if you could improve your model though. What happens when a video has more than three actors?

Using an intersection table video_actors

  • video_id
  • actor_id

would allow to do that.


Use joins:

SELECT  
    `act1`.`name`,
    `act1`.`surname`,
    `act2`.`name`,
    `act2`.`surname`,
    `act3`.`name`,
    `act3`.`surname`
FROM `videos`
JOIN `actors` AS act1 ON `act1`.`id` = `videos`.`id_actor1`
LEFT JOIN `actors` AS act2 ON `act2`.`id` = `videos`.`id_actor2`
LEFT JOIN `actors` AS act3 ON `act3`.`id` = `videos`.`id_actor3`
WHERE `videos`.`ident` = 'somethink' 


Because afaik MySQL does Short-circuit evaluation when evaluating the where clause and thus creating the Cartesian product, in your case between the other actor tables. As others already mentioned, LEFT JOIN is much more applicable.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号