MySQL optimised code for 2 tables? - php

I have 2 tables,
Table1: id,int1,int2,int3,int4,int5
Table2: integers (autoincrement),blobdata
The query I want to use is given the id I want to get the blobdata from table2 associated with the 5 integers in table1. I've only ever used one table in mysql so have no idea how to do this properly.
Is it possible?
EDIT: id is username, integers in table2 is just integers. but have not built the tables yet, so can change if need to.

select t1.id, t1.int1, t1.int2 ... t2.blobdata
from table1 t1, table2 t2
where t1.id = t2.id and t1.id = <your input id>
Assuming the auto increment integer column is the id that match the id on table1.
t2.id - or any other name you will call this column of course.

What you need is to set a foreign key in table1, which would contain the id of the blobdata you want to point to.
Take a look here: http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

Related

SELECT emails FROM table 1 only if table 2 doesn't have value [duplicate]

table1 (id, name)
table2 (id, name)
Query:
SELECT name
FROM table2
-- that are not in table1 already
SELECT t1.name
FROM table1 t1
LEFT JOIN table2 t2 ON t2.name = t1.name
WHERE t2.name IS NULL
Q: What is happening here?
A: Conceptually, we select all rows from table1 and for each row we attempt to find a row in table2 with the same value for the name column. If there is no such row, we just leave the table2 portion of our result empty for that row. Then we constrain our selection by picking only those rows in the result where the matching row does not exist. Finally, We ignore all fields from our result except for the name column (the one we are sure that exists, from table1).
While it may not be the most performant method possible in all cases, it should work in basically every database engine ever that attempts to implement ANSI 92 SQL
You can either do
SELECT name
FROM table2
WHERE name NOT IN
(SELECT name
FROM table1)
or
SELECT name
FROM table2
WHERE NOT EXISTS
(SELECT *
FROM table1
WHERE table1.name = table2.name)
See this question for 3 techniques to accomplish this
I don't have enough rep points to vote up froadie's answer. But I have to disagree with the comments on Kris's answer. The following answer:
SELECT name
FROM table2
WHERE name NOT IN
(SELECT name
FROM table1)
Is FAR more efficient in practice. I don't know why, but I'm running it against 800k+ records and the difference is tremendous with the advantage given to the 2nd answer posted above. Just my $0.02.
SELECT <column_list>
FROM TABLEA a
LEFTJOIN TABLEB b
ON a.Key = b.Key
WHERE b.Key IS NULL;
https://www.cloudways.com/blog/how-to-join-two-tables-mysql/
This is pure set theory which you can achieve with the minus operation.
select id, name from table1
minus
select id, name from table2
Here's what worked best for me.
SELECT *
FROM #T1
EXCEPT
SELECT a.*
FROM #T1 a
JOIN #T2 b ON a.ID = b.ID
This was more than twice as fast as any other method I tried.
Watch out for pitfalls. If the field Name in Table1 contain Nulls you are in for surprises.
Better is:
SELECT name
FROM table2
WHERE name NOT IN
(SELECT ISNULL(name ,'')
FROM table1)
You can use EXCEPT in mssql or MINUS in oracle, they are identical according to :
http://blog.sqlauthority.com/2008/08/07/sql-server-except-clause-in-sql-server-is-similar-to-minus-clause-in-oracle/
That work sharp for me
SELECT *
FROM [dbo].[table1] t1
LEFT JOIN [dbo].[table2] t2 ON t1.[t1_ID] = t2.[t2_ID]
WHERE t2.[t2_ID] IS NULL
You can use following query structure :
SELECT t1.name FROM table1 t1 JOIN table2 t2 ON t2.fk_id != t1.id;
table1 :
id
name
1
Amit
2
Sagar
table2 :
id
fk_id
email
1
1
amit#ma.com
Output:
name
Sagar
All the above queries are incredibly slow on big tables. A change of strategy is needed. Here there is the code I used for a DB of mine, you can transliterate changing the fields and table names.
This is the strategy: you create two implicit temporary tables and make a union of them.
The first temporary table comes from a selection of all the rows of the first original table the fields of which you wanna control that are NOT present in the second original table.
The second implicit temporary table contains all the rows of the two original tables that have a match on identical values of the column/field you wanna control.
The result of the union is a table that has more than one row with the same control field value in case there is a match for that value on the two original tables (one coming from the first select, the second coming from the second select) and just one row with the control column value in case of the value of the first original table not matching any value of the second original table.
You group and count. When the count is 1 there is not match and, finally, you select just the rows with the count equal to 1.
Seems not elegant, but it is orders of magnitude faster than all the above solutions.
IMPORTANT NOTE: enable the INDEX on the columns to be checked.
SELECT name, source, id
FROM
(
SELECT name, "active_ingredients" as source, active_ingredients.id as id
FROM active_ingredients
UNION ALL
SELECT active_ingredients.name as name, "UNII_database" as source, temp_active_ingredients_aliases.id as id
FROM active_ingredients
INNER JOIN temp_active_ingredients_aliases ON temp_active_ingredients_aliases.alias_name = active_ingredients.name
) tbl
GROUP BY name
HAVING count(*) = 1
ORDER BY name
See query:
SELECT * FROM Table1 WHERE
id NOT IN (SELECT
e.id
FROM
Table1 e
INNER JOIN
Table2 s ON e.id = s.id);
Conceptually would be: Fetching the matching records in subquery and then in main query fetching the records which are not in subquery.
First define alias of table like t1 and t2.
After that get record of second table.
After that match that record using where condition:
SELECT name FROM table2 as t2
WHERE NOT EXISTS (SELECT * FROM table1 as t1 WHERE t1.name = t2.name)
I'm going to repost (since I'm not cool enough yet to comment) in the correct answer....in case anyone else thought it needed better explaining.
SELECT temp_table_1.name
FROM original_table_1 temp_table_1
LEFT JOIN original_table_2 temp_table_2 ON temp_table_2.name = temp_table_1.name
WHERE temp_table_2.name IS NULL
And I've seen syntax in FROM needing commas between table names in mySQL but in sqlLite it seemed to prefer the space.
The bottom line is when you use bad variable names it leaves questions. My variables should make more sense. And someone should explain why we need a comma or no comma.
I tried all solutions above but they did not work in my case. The following query worked for me.
SELECT NAME
FROM table_1
WHERE NAME NOT IN
(SELECT a.NAME
FROM table_1 AS a
LEFT JOIN table_2 AS b
ON a.NAME = b.NAME
WHERE any further condition);

Query for Selecting except values with two column

i have two tables.
First table column
value is
1,2,7.
Second table column
value is 1,2,3,4,5,6,7,8,9,10.
what i needed is i want to fetch second table values except first table values.Result should be 3,4,5,6,8,9,10.I do no what is the query for this one.Please help me.
SELECT value FROM secondtable WHERE value NOT IN (SELECT value FROM firsttable)
The standard SQL is to use NOT IN or NOT EXISTS:
select t2.*
from t2
where not exists (select 1 from table1 t1 where t1.value = t2.value);

Slow process for IN clause in MySql SELECT Query that contain large numbers

I have written a query to fetch details from table1, which has this condition clause:
IN(number1,number2......
Up to 323 entries so far now. These numbers are the primary key of table1, which has been extracted from table2 and passed into the IN condition clause.
Due to this my query slows down and takes 13 seconds to run. Is there any other way to overcome this? If I give some constant values (like PK id), the query works in usual time.
You can also do it using LEFT JOIN:
For example:
SELECT T1.*
FROM Table1 T1 LEFT JOIN
Table2 T2 ON T1.numberfield = T2.numberfield
WHERE T2.someotherfield IS NOT NULL
This does the exact job of the query with IN.
try below-
select a.* from table1 a join table2 b
on a.parent_id=b.id;
Note: parent_id should be indexed in table 1 and assuming id will be prmary key of table b means already indexed.

How to join two large tables with different strings

I have two tables
table1
customer_id
101
102
103
and table2
customer_id country_id
AO-101 1
AO-102 2
AO-103 3
both the tables are very large tables I have used CONCAT(table1.customer_id) for joining with the table2
all the fields stated above are index fields
joining them and getting all the customer of country 1 is taking lot of time
Can anyone help me please?
You can try this mate:
SELECT * FROM table1
JOIN table2 ON CONCAT('AO-', table1.customer_id) = table2.customer_id
WHERE table2.country_id = 1;
or this one:
SELECT * FROM table2
JOIN (
SELECT CONCAT('AO-', customer_id) AS in_customer_id, table1.* FROM table1
) AS table1 ON table1.in_customer_id = table2.customer_id
WHERE table2.country_id = 1;
I believe the problem you are running into is HOW an index is stored.
The way to understand this is to literally think of a PHYSICAL index that sits NEXT to the table as alookup.
If you do something like "create index index_1 on table1(column_1)", what this is does is stores this right next to the table and before you run a query referencing that table, the the DBMS looks over the tables and your query and determines the best way to query the tables based on indexes, table sizes, etc.
Now, the index stores literally the exact value in the exact DATATYPE as the field, unless you cast the index as a different datatype.
Right now you are joining an integer field to a character field and right there, you are not going to get the same performance from the index as you cannot use the index purely as such - it has to be translated on the fly, so to speak.
So what I would do is type something like:
create index on table2(cast(replace(customer_id,'AO-','') as integer));
This should store an integer value as the INDEX so when joined to the integer primary key, the index should run fine.
Also, why don't you just store the same integer value instead of adding this 'AO-' thing?
mysql uses CONCAT() to concatenate strings
So we use following query:
ON tableTwo.query = concat('category_id=',tableOne.category_id)
Hope this helps to you.
You can write a subquery like this:
SELECT * FROM table1 JOIN
(SELECT SUBSTRING_INDEX(customer_id, '-', -1) AS customer_id, country_id
FROM table2) t2 USING customer_id;
I haven't tried it, but you might also be able to join directly:
ON SUBSTRING_INDEX(table2.customer_id, '-', -1) = table1.customer_id
Try This Code It's Working.
select * from table4 t4, table3 t3 where t4.cus_id in (CONCAT('A0-', t3.cus_id)) && t4.country=1 ;

Find non-existing ID's using SELECT NOT IN?

I have a list of ID's, comma separated stored as string.
123,456,789
I was previously using something like this to pull data for each row in the database where each ID was present:
SELECT id, name FROM line_item WHERE id IN (123,456,789)
However, I want to only determine the ID's where they do not exist in the database. E.g. check the table to return all ID's provided that do not exist in the DB.
I tried NOT IN assuming it would work, but of course, all I got was every ID that did not match my sample, which was massive (thousands of rows, small number of ID's that we typically need to check for).
SELECT id FROM line_item WHERE id NOT IN (123,456,789)
For example:
Table: ID
111
222
333
444
555
777
999
String:
111,222,666,888,999
Query should return:
666,888
Using MySQL, can I find those values not present without using PHP.
You can create additional table populated with desired id values, and use query with LEFT JOIN and WHERE clauses -
CREATE TABLE temp_table(id INT);
INSERT INTO temp_table VALUES(123),(456),(789);
SELECT t1.id FROM temp_table t1
LEFT JOIN line_item t2
ON t1.id = t2.id
WHERE t2.id IS NULL;
Another variant:
SELECT t1.id FROM (SELECT 123 id UNION SELECT 456 UNION SELECT 789) t1
LEFT JOIN line_item t2
ON t1.id = t2.id
WHERE t2.id IS NULL;
NOT IN will take the values in the parentheses and cause the query to, as you said, give you all other ids.
I do not know if there is a way to do this with several numbers simultaneously - but this is how you could do it with one:
SELECT id, name, description
FROM line_item
WHERE 1 NOT IN (SELECT id FROM line_item) // Replace 1 with your numbers in a loop
On Postgresql you can use the generate_series(i,j) function. For example to find the non-existent integers in the id column you can write:
select i from generate_series(
(select min(id) from line_item),(select max(id) from line_item)
) as i
where i not in (select id from line_item);
If you want to use this query to find the first available integer to use as an id, you can use this query:
select min(i) from generate_series(
(select min(id) from line_item),(select max(id) from line_item)+1
) as i
where i not in (select id from line_item);

Categories