简体   繁体   中英

How to use subqueries in MySQL

I have two tables.

Table user :

CREATE TABLE IF NOT EXISTS `user` (
  `user_id` int(20) NOT NULL AUTO_INCREMENT,
  `ud_id` varchar(50) NOT NULL,
  `name` text NOT NULL,
  `password` text NOT NULL,
  `email` varchar(200) NOT NULL,
  `image` varchar(150) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB

and mycatch :

CREATE TABLE IF NOT EXISTS `mycatch` (
  `catch_id` int(11) NOT NULL AUTO_INCREMENT,
  `catch_name` text NOT NULL,
  `catch_details` text NOT NULL,
  `longitude` float(10,6) NOT NULL,
  `latitude` float(10,6) NOT NULL,
  `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `image` varchar(150) NOT NULL,
  `user_id` int(20) NOT NULL,
  PRIMARY KEY (`catch_id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB;
ALTER TABLE `mycatch`
  ADD CONSTRAINT `mycatch_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE;

My goal is: I want to retrieve longitude and latitude from mycatch against given ud_id (from user ) and catch_id (from mycatch ) where ud_id = given ud_id and catch_id > given catch_id .

I used the query but fail to retrieve

SELECT ud_id=$ud_id FROM user
WHERE user_id =
(
SELECT user_id,longitude,latitude from mycatch
WHERE catch_id>'$catch_id'
)

The error is:

#1241 - Operand should contain 1 column(s)

First, try not to use subqueries at all, they're very slow in MySQL.

Second, a subquery wouldn't even help here. This is a regular join (no, Mr Singh, not an inner join):

SELECT ud_id FROM user, mycatch
WHERE catch_id>'$catch_id'
AND user.user_id = mycatch.user_id
 Select m.longitude,m.latitude from user u left join mycatch m 
on u.user_id =m.user_id 
where u.ud_id=$ud_id and 
m.catch_id >$catch_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM