带有Where子句的SQL UNION是第一个选择的结果

时间:2014-04-09 10:09:42

标签: mysql sql join union

我需要执行以下查询:

SELECT (COL1,COL2, ClientID)
FROM Jobs
Union
SELECT (ClientID,COL2,COL3)
FROM Clients WHERE (the ClientID= ClientID my first select)

我真的被困了,我一直在尝试加入联盟和工会,并且不知道该怎么做。

* 编辑 *查询以创建作业表

CREATE TABLE IF NOT EXISTS `jobs` (
  `JobID` int(11) NOT NULL AUTO_INCREMENT,
  `Title` varchar(32) NOT NULL,
  `Trade` varchar(32) NOT NULL,
  `SubTrade` varchar(300) NOT NULL,
  `Urgency` tinyint(4) NOT NULL,
  `DatePosted` int(11) NOT NULL,
  `Description` varchar(500) NOT NULL,
  `Photo` longblob,
  `Photo2` longblob,
  `Address` varchar(600) NOT NULL,
  `ShowAddress` tinyint(4) NOT NULL,
  `ShowExact` tinyint(4) NOT NULL,
  `JobStatus` tinyint(4) NOT NULL,
  `Longitude` double NOT NULL,
  `Latitude` double NOT NULL,
  `ClientID` int(11) NOT NULL,
  `TradesmanID` int(11) DEFAULT NULL,
  PRIMARY KEY (`JobID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=171 ;

和创建客户端表的查询是

CREATE TABLE IF NOT EXISTS `clients` (
  `ClientID` int(11) NOT NULL AUTO_INCREMENT,
  `FName` varchar(32) NOT NULL,
  `SName` varchar(32) NOT NULL,
  `Email` varchar(32) NOT NULL,
  `HomePhone` int(11) NOT NULL,
  `Mobile` varchar(30) NOT NULL,
  `Address` varchar(100) NOT NULL,
  `County` varchar(32) NOT NULL,
  `PostCode` varchar(32) NOT NULL,
  `UserName` varchar(32) NOT NULL,
  `Password` varchar(32) NOT NULL,
  `NotificationID` varchar(255) NOT NULL,
  PRIMARY KEY (`ClientID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=96 ;

3 个答案:

答案 0 :(得分:1)

  SELECT 
Clients.ClientID
,Clients.NotificationID
,Clients.Email
,Clients.Mobile
,Clients.HomePhone 
,Jobs.JobID
,Jobs.Title
,Jobs.Trade
,Jobs.Address               AS JobAddress
,Jobs.Urgency
,Jobs.DatePosted
,Jobs.Description
,Jobs.Photo
,Jobs.Photo2
,Jobs.ShowAddress
,Jobs.ShowExact
,Jobs.JobStatus
    ,Jobs.TradesmanID
    ,Jobs.Longitude
    ,Jobs.Latitude

 FROM
    Clients
 INNER JOIN 
    Jobs
        on Clients.ClientId = Jobs.ClientId

答案 1 :(得分:1)

这个怎么样?有一些重复,即第二个联合中的select子句复制第一个语句,但它会起作用。

SELECT COL1,COL2, ClientID
FROM Jobs
Union
SELECT ClientID,COL2,COL3
FROM Clients WHERE (Select ClientID FROM Jobs)

答案 2 :(得分:1)

试试这个:

     SELECT c.ClientID, c.COL2, c.COL3, x.col1
        FROM Clients c inner join 
                         (select clientId, 
                                 min(col1) as col1 
                          from jobs 
                          group by clientId) x
           on c.clientId = x.clientId