2017-08-04 99 views
1

我有一个脚本,在检查员工的时候可以看到彼此的库存库存,并链接到他们的个人库存位置,因此每个在员工中检查的人员都可以看到哪些库存库存不同位置。不过,我想主要的股票(的1 ID,这是没有附加到员工)总是被显示,但我不能得到查询权,因为该where语句之一显然是不正确的:基于多个条件的SQL查询

`stock_locations`.`location_id` = 1 AND 
`workschedule`.`checkedIn` = 1 AND 

记住,主股票没有链接到员工,所以它不出现在workschedule表。如果我删除了第一个陈述,它清楚地显示了所有员工在他们所在位置的入住情况,但是这并没有给我提供主要股票。如果我删除第二个陈述,它只显示我的主要股票。

我该如何解决SQL中的这个问题?这是顺便说一句完整的声明:

SELECT 
    `item_quantities`.`item_id`, 
    `stock_locations`.`location_name`, 
    `item_quantities`.`quantity`, 
    `people`.`first_name` 
FROM 
    `item_quantities` 
JOIN `stock_locations` ON `item_quantities`.`location_id` = `stock_locations`.`location_id` 
JOIN `items` ON `item_quantities`.`item_id` = `items`.`item_id` 
LEFT JOIN `workschedule` ON `workschedule`.`linked_storage` = `stock_locations`.`location_id` 
LEFT JOIN `people` ON `workschedule`.`employee_id` = `people`.`person_id` 
WHERE 
    `stock_locations`.`location_id` = 1 AND 
    `workschedule`.`checkedIn` = 0 AND 
    `items`.`unit_price` != 0 AND 
    `items`.`deleted` = 0 AND 
    `stock_locations`.`deleted` = 0 NULL 

在此先感谢!

回答

2

使它成为parens内的OR语句。

(`stock_locations`.`location_id` = 1 OR `workschedule`.`checkedIn` = 1) AND 

这将返回与主股票或员工匹配的所有记录。

1

您需要使用OR运算符。显然,两件事情不可能同时发生,所以你需要指定每一组可接受的条件。

SELECT 
    `item_quantities`.`item_id`, 
    `stock_locations`.`location_name`, 
    `item_quantities`.`quantity`, 
    `people`.`first_name` 
FROM 
    `item_quantities` 
    JOIN `stock_locations` 
    ON `item_quantities`.`location_id` = `stock_locations`.`location_id` 
    JOIN `items` 
    ON `item_quantities`.`item_id` = `items`.`item_id` 
    LEFT JOIN `workschedule` 
    ON `workschedule`.`linked_storage` = `stock_locations`.`location_id` 
    LEFT JOIN `people` 
    ON `workschedule`.`employee_id` = `people`.`person_id` 
WHERE 
    `stock_locations`.`location_id` = 1 
    OR (
     AND `workschedule`.`checkedIn` = 1 
     AND `items`.`unit_price`  != 0 
     AND `items`.`deleted`   = 0 
     AND `stock_locations`.`deleted` = 0 
     NULL 
    ) 
0

您有LEFT JOIN,但您的WHERE子句将它们变成内部连接。修复可能会解决您的问题:

SELECT . . . 
FROM item_quantities iq JOIN 
    stock_locations sl 
    ON iq.`location_id` = sl.`location_id` JOIN 
    items i 
    ON iq.`item_id` = i.`item_id` LEFT JOIN 
    workschedule ws 
    ON ws.`linked_storage` = sl.`location_id` AND 
     ws.`checkedIn` = 0 LEFT JOIN 
--------^ 
    people p 
    ON ws.`employee_id` = p.`person_id` 
WHERE sl.`location_id` = 1 AND 
     i.`unit_price` != 0 AND 
     i.`deleted` = 0 AND 
     sl.`deleted` = 0