I want to execute a query where I can find one ID in a list of ID.
table user
id_user | name | id_site
-------------------------
1 | james | 1, 2, 3
1 | brad | 1, 3
1 | suko | 4, 5
and my query (doesn't work)
SELECT * FROM `user` WHERE 3 IN (`id_site`)
This query work (but doesn't do the job)
SELECT * FROM `user` WHERE 3 IN (1, 2, 3, 4, 6)
That's not how IN works. I can't be bothered to explain why, just read the docs
Try this:
SELECT * FROM `user` WHERE FIND_IN_SET(3,`id_site`)
Note that this requires your data to be 1,2,3, 1,3 and 4,5 (ie no spaces). If this is not an option, try:
SELECT * FROM `user` WHERE FIND_IN_SET(3,REPLACE(`id_site`,' ',''))
Alternatively, consider restructuring your database. Namely:
CREATE TABLE `user_site_links` (
`id_user` INT UNSIGNED NOT NULL,
`id_site` INT UNSIGNED NOT NULL,
PRIMARY KEY (`user_id`,`site_id`)
);
INSERT INTO `user_site_links` VALUES
(1,1), (1,2), (1,3),
(2,1), (2,3),
(3,4), (3,5);
SELECT * FROM `user` JOIN `user_site_links` USING (`id_user`) WHERE `id_site` = 3;
Try this: FIND_IN_SET(str,strlist)
NO! For relation databases
Your table doesn't comfort first normal form ("each attribute contains only atomic values, and the value of each attribute contains only a single value from that domain") of a database and you:
use string field to contain numbers
store multiple values in one field
To work with field like this you would have to use FIND_IN_SET() or store data like ,1,2,3, (note colons or semicolons or other separator in the beginning and in the end) and use LIKE "%,7,%" to work in every case. This way it's not possible to use indexes[1][2].
Use relation table to do this:
CREATE TABLE user_on_sites(
user_id INT,
site_id INT,
PRIMARY KEY (user_id, site_id),
INDEX (user_id),
INDEX (site_id)
);
And join tables:
SELECT u.id, u.name, uos.site_id
FROM user_on_sites AS uos
INNER JOIN user AS u ON uos.user_id = user.id
WHERE uos.site_id = 3;
This way you can search efficiently using indexes.
The problem is that you are searching within several lists.
You need something more like:
SELECT * FROM `user` WHERE id_site LIKE '%3%';
However, that will also select 33, 333 and 345 so you want some more advanced text parsing.
The WHERE IN clause is useful to replace many OR conditions.
For exemple
SELECT * FROM `user` WHERE id IN (1,2,3,4)
is cleaner than
SELECT * FROM `user` WHERE id=1 OR id=2 OR id=3 OR id=4
You're just trying to use it in a wrong way.
Correct way :
WHERE `field` IN (list_item1, list_item2 [, list_itemX])
Related
This is my query to get filter data from user table where category will fetch from another table.
SELECT * FROM jobfia_users
WHERE country_id='4'
and user_id IN (SELECT worker_id
FROM jobfia_worker_skills
WHERE skill_id = '42'
)
This is not giving any error, but not return any row also.
while there are lots of records are available in table using this filter.
Can any one help please ?
Additionally to the quotes surrounding your INT ids, your query will be better expressed like this :
SELECT u.*
FROM jobfia_users u
INNER JOIN jobfia_worker_skills ws
ON ws.worker_id=u.user_id AND ws.skill_id = 42
WHERE u.country_id=4
If your country_id and skill_id are int type, remove ' around values.
SELECT * FROM jobfia_users
WHERE country_id=4
and user_id IN (SELECT worker_id
FROM jobfia_worker_skills
WHERE skill_id = 42
)
Tested your code with and without '' and it works. Make sure you have data and you did not misspell some column name.
Maybe you have collision of some column names. Try to use this syntax:
\`table_name\`.\`column_name\`
Code:
SELECT *
FROM `jobfia_users`
WHERE `jobfia_users`.`country_id`='4'
AND `jobfia_users`.`user_id` IN (SELECT `jobfia_worker_skills`.`worker_id`
FROM `jobfia_worker_skills`
WHERE `jobfia_worker_skills`.`skill_id` = '42')
Say, I have a table with five columns col1, col2, col3, col4 and user_id. Now, I have an array of user_id values, say a thousand. I want to insert thousand of records where only distinct column value is user_id. If there is a simplier way rather than make a thousand of ('col1value','col2value','col3value','col4value',someUserId) and concatenate them in single insert into tbl (col1,col2,col3,col4,user_id) values query?
Update: I guess it needs some clarification
So here's simple example. Let's say I have an events table with fields event and user_id. Some call event occurs for users with id 1, 2, 5, 101, 233, 422 and 1000. So I need to insert 7 records into table so it should look like
+-------+---------+
| event | user_id |
|-------|---------|
| call | 1 |
| call | 2 |
| call | 5 |
| call | 101 |
| call | 233 |
| call | 422 |
| call | 1000 |
+-------+---------+
I want to do it as efficiently database-wise as possible. So far, I think I have to make such SQL query:
insert into events (event,user_id) values ('call',1),('call',2),('call',5),('call',101),('call',233),('call',422),('call',1000);
then perform a single query
But maybe there is some more simple and efficient way? Maybe something with SQL parameters or such?
I understand your question that you have a high number of different user_id values that you want to insert, but for each new record you want the same values for col1, col2, col3 and col4.
The easiest way to achieve this would be to set a DEFAULT value for each of the columns:
ALTER TABLE mytable CHANGE `col1` `col1` INTEGER NOT NULL DEFAULT 1234
This sets the default value for col1 to 1234. I assumed the column to be of data type INTEGER, you need to change it accordingly.
If changing the table is not an option for you, then you could still build an insert statement that would insert all records in a single transaction:
$user_ids = array(5,6, 7, 8, 9, 10); // these are the user ids you want to insert
$default_vals = array(1, 2, 3, 4); // These are the default values used for col1, col2, col3 and col4
$con = new mysqli('mydomain', 'myuser', 'mypw', 'mydb');
$rows = array();
foreach ($user_ids as $id)
$rows[] = "(".implode(',', $default_vals).",$id)";
$sql = "INSERT INTO mytbl (col1, col2, col3, col4, id) VALUES " . implode(',', $rows) . ";";
$con->query($sql);
Or, if for academic reason you'd rather write a single INSERT statement to do the whole job, you could write:
INSERT INTO mytbl (col1, col2, col3, col4, id)
SELECT * FROM
(SELECT 1, 2, 3, 4) AS DEFAULT_VALS,
(SELECT 5
UNION SELECT 6
UNION SELECT 7
UNION SELECT 8
UNION SELECT 9) AS USER_IDS
However, the last approach really isn't very nice. Neither in terms of readability nor of performance.
Edit
I made a quick benchmark for you:
Inserting 10k different records like in my PHP sample took 1.5086660385132 seconds on my webserver.
The SELECT INTO approach with 10k UNIONs took 3.3481941223145 seconds.
Easy choice, though.
Use :
INSERT INTO tbl (col1,col2,col3,col4,user_id)
VALUES
(1,2,3,4,1000),
(2,3,4,5,1000),
(6,7,8,9,1000),
(1,2,3,4,1234),
(4,3,2,1,1235);
Create unique index on user_id field. use INSERT IGNORE or INSERT ... ON DUPLICATE KEY UPDATE for ignoring duplicate insertion of user_id.
For details, kindly refer MySQL documentation.
http://dev.mysql.com/doc/refman/5.6/en/insert.html
I have 3 tables course, grade and evaluation. I want comparing two tables grade and evaluation . if the data in the table grade does not exist in the table evaluation , then the data will appear (output)
" select Grade.ID_Courses,Course.ID_Courses,Grade.NAME,
Course.NAME, Grade.ID_Courses,
Evaluation.NAME,
Evaluation.Year,
Grade.Year
from Grade, Course, Evaluation
WHERE
Grade.ID_Courses=Course.ID_Courses AND
Grade.NAME=JOHN and
Grade.Year=1 and
Evaluation.NAME=GRADE.NAME and
Grade.ID_Courses NOT IN (SELECT ID_Courses FROM Evaluation where NAME=JOHN and Year=1 )
GROUP BY Grade.ID_Courses"
the problem is when the name john is not in the table evaluation then there is no output comes out .
Avoid NOT IN like the plague if
SELECT ID_Courses FROM Evaluation where `NAME`='JOHN' and Year=1
could ever contain NULL. Instead, use NOT EXISTS or Left Joins
use explicit joins, not 1980's style joins using the WHERE clause
To illustrate the misery of NOT IN:
SQL NOT IN () danger
create table mStatus
( id int auto_increment primary key,
status varchar(10) not null
);
insert mStatus (status) values ('single'),('married'),('divorced'),('widow');
create table people
( id int auto_increment primary key,
fullName varchar(100) not null,
status varchar(10) null
);
Chunk1:
truncate table people;
insert people (fullName,`status`) values ('John Henry','single');
select * from mstatus where `status` not in (select status from people);
** 3 rows, as expected **
Chunk2:
truncate table people;
insert people (fullName,`status`) values ('John Henry','single'),('Kim Billings',null);
select * from mstatus where status not in (select status from people);
no rows, huh?
Obviously this is 'incorrect'. It arises from SQL's use of three-valued logic,
driven by the existence of NULL, a non-value indicating missing (or UNKNOWN) information.
With NOT IN, Chunk2 it is translated like this:
status NOT IN ('married', 'divorced', 'widowed', NULL)
This is equivalent to:
NOT(status='single' OR status='married' OR status='widowed' OR status=NULL)
The expression "status=NULL" evaluates to UNKNOWN and, according to the rules of three-valued logic,
NOT UNKNOWN also evaluates to UNKNOWN. As a result, all rows are filtered out and the query returns an empty set.
Possible solutions include:
select s.status
from mstatus s
left join people p
on p.status=s.status
where p.status is null
or use not exists
Try using joins to solve this
select g.*, e.*,c.* from
grade g inner join evaluation e on
g.ID_COURSES <> e.ID_COURSES and g.year <> e.year
inner join COURSE c on c.ID_COURSES = g.ID_COURSES
;
I have table (about 80'000 rows), looks like
id, parentId, col1, col2, col3...
1, null, 'A', 'B', 'C'
2, 1, ...
3, 1, ...
4, null, ...
5, 4, ...
(one level parent - child only)
and I need get all dependent rows -
SELECT ...
FROM table
WHERE id = :id OR parentId = :id OR id IN (
SELECT parentId
FROM table
WHERE id = :id
)
but why this request working slowly instead 2 request - if I get parentId on php first?
$t = executeQuery('SELECT parentId FROM table WHERE id = :Id;', $id);
if ($t) {
$id = $t;
}
$t = executeQuery('SELECT * FROM table WHERE id = :id OR parentId = :id ORDER BY id;', $id);
PS: max depends rows < 70
PPS:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY product ALL PRIMARY,parentId NULL NULL NULL 73415 Using where
2 DEPENDENT SUBQUERY product const PRIMARY,parentId PRIMARY 4 const 1
Change the IN for an equal =
SELECT ...
FROM table
WHERE id = :id OR parentId = :id OR id = (
SELECT parentId
FROM table
WHERE id = :id
)
or change it to a join:
SELECT ...
FROM table
inner join (
SELECT parentId
FROM table
WHERE id = :id
) s on s.parentID = table.id or s.parentID = table.parentID
Well, in the first case, MySQL need to create an intermediate result, store it in memory and then iterate over it to find all the relevant id in the table. In the second way, assuming you correctly created an index on id and parent id, it simply go straigth to the index, find the relevant rows, and send you back the result immediately.
UNION works faster for this case
this allows first query to user UNION INDEX and second just uses inner join, then merges results.
SELECT *
FROM `table`
WHERE id = :id OR parentId = :id
UNION
SELECT t1.*
FROM `table` t1 JOIN `table` t2 ON t2.parentId = t1.id AND t2.id = :id
An EXPLAIN might shed some more light on the problem for you.
Look into EXISTS, or rewriting your query as a JOIN.
It's a long shot but in first case you have "IN" statement of the WHERE part of the query. Maybe MySQL tries to optimize the query as if there would be multiple options and in the second case there is no IN part, so the compiled query is more straight forward for the database - thus utilizing the indexes in better manner.
Basically for 2 queries on the same connection the overhead of performing the queries should be minimal and irelevant in this case. Also subqueries in general are not very optimizable by the query parser. Try using JOIN instead (if possible).
Hello i have a question on picking random entries from a database. I have 4 tables, products, bids and autobids, and users.
Products
-------
id 20,21,22,23,24(prime_key)
price...........
etc...........
users
-------
id(prim_key)
name user1,user2,user3
etc
bids
-------
product_id
user_id
created
autobids
--------
user_id
product_id
Now a multiple users can have an autobid on an product. So for the next bidder I want to select a random user from the autobid table
example of the query in language:
for each product in the autobid table I want a random user, which is not the last bidder.
On product 20 has user1,user2,user3 an autobidding.
On product 21 has user1,user2,user3 an autobidding
Then I want a resultset that looks for example like this
20 – user2
21 – user3
Just a random user. I tried miximg the GOUP BY (product_id) and making it RAND(), but I just can't get the right values from it. Now I am getting a random user, but all the values that go with it don't match.
Can someone please help me construct this query, I am using php and mysql
The first part of the solution is concerned with identifying the latest bid for each product: these eventually wind up in temporary table "latest_bid".
Then, we assign randon rank values to each autobid for each product - excluding the latest bid for each product. We then choose the highest rank value for each product, and then output the user_id and product_id of the autobids with those highest rank values.
create temporary table lastbids (product_id int not null,
created datetime not null,
primary key( product_id, created ) );
insert into lastbids
select product_id, max(created)
from bids
group by product_id;
create temporary table latest_bid ( user_id int not null,
product_id int not null,
primary key( user_id, product_id) );
insert into latest_bid
select product_id, user_id
from bids b
join lastbids lb on lb.product_id = b.product_id and lb.created = b.created;
create temporary table rank ( user_id int not null,
product_id int not null,
rank float not null,
primary key( product_id, rank ));
# "ignore" duplicates - it should not matter
# left join on latest_bid to exclude latest_bid for each product
insert ignore into rank
select user_id, product_id, rand()
from autobids a
left join latest_bid lb on a.user_id = lb.user_id and a.product_id = lb.product_id
where lb.user_id is null;
create temporary table choice
as select product_id,max(rank) choice
from rank group by product_id;
select user_id, res.product_id from rank res
join choice on res.product_id = choice.product_id and res.rank = choice.choice;
You can use the LIMIT statement in conjunction with server-side PREPARE.
Here is an example that selects a random row from the table mysql.help_category:
select #choice:= (rand() * count(*)) from mysql.help_category;
prepare rand_msg from 'select * from mysql.help_category limit ?,1';
execute rand_msg using #choice;
deallocate prepare rand_msg;
This will need refining to prevent #choice becoming zero, but the general idea works.
Alternatively, your application can construct the count itself by running the first select, and constructing the second select with a hard-coded limit value:
select count(*) from mysql.help_category;
# application then calculates limit value and constructs the select statement:
select * from mysql.help_category limit 5,1;