簡體   English   中英

使用JOIN或其他解決方案進行MySQL查詢

[英]MySQL query with JOIN or different solution

我對此查詢有疑問:

select start, end, surname, name, id from employee, absences where surname LIKE '$surname%' and name LIKE '$name%' and start LIKE '$start%' and name LIKE '$end%' order by start ASC 

我知道這不是搜索的好方法。 我嘗試為此使用JOIN,但失敗了。 我有兩個表:缺勤和雇員,僅通過FK連接,這給了我太多結果(相乘)。

如何為此使用聯接? 還是有其他解決方案?

Tables_

CREATE TABLE IF NOT EXISTS `absences` (
`absences_ID` int(11) NOT NULL,
  `employee_FK` int(11) NOT NULL,
  `start` date NOT NULL,
  `end` date NOT NULL,
  `approved` tinyint(1) NOT NULL DEFAULT '0',
  `approved_date` date DEFAULT NULL,
  `comment` varchar(100) NOT NULL,
  `type_FK` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1371 DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `employee` (
`employee_ID` int(11) NOT NULL,
  `id` int(11) NOT NULL,
  `name` varchar(30) DEFAULT NULL,
  `surname` varchar(30) DEFAULT NULL,
  `password` varchar(60) NOT NULL,
  `email` varchar(255) NOT NULL,
  `on_off_FK` int(11) NOT NULL,
  `inactive` tinyint(1) NOT NULL DEFAULT '1',
  `admin` tinyint(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=latin1;

與條件一起使用

    select a.start, a.end, e.surname, e.name, e.id 
from employee e
JOIN absences a ON e.employee_id=a.employeefk
where e.surname LIKE '$surname%' and e.name LIKE '$name%' and a.start LIKE'$start%' and a.end LIKE '$end%'
order by a.start ASC

試試這個我已經根據您的表更新了

現在試試這個

select a.start, a.end, e.surname, e.name, e.id 
from employee e
JOIN absences a ON e.id=a.Id
where e.surname LIKE '$surname%' and e.name LIKE '$name%' and a.start LIKE'$start%' and a.end LIKE '$end%'
order by a.start ASC

試試這個我已經根據您的表更新了

試試這個...我添加了一些占位符,您需要在其中放置提取所需的列以及要使用的連接條件

select {column name comma separated} from employee e
INNER JOIN absences ON e.id=absences.id {here u need to specify which column to use for joining two column}
where surname LIKE '$surname%' and name LIKE '$name%' and start LIKE '$start%' and name LIKE '$end%'
order by start ASC

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM