PDO Select from table WHERE url != (SELECT) - sql

I have 2 db tables - one is including all the entries, the other one is the "blacklist" - means i want to select all values excluding the entries of table 2
$req = "SELECT * FROM table1 WHERE link_id != (SELECT id FROM table2)";
$stmt = $pdo->query($req);
foreach($stmt as $data) {
echo $data['link_id']."<br>";
}
Can anyone help me out?

You could try NOT IN, like so:
$req = "SELECT * FROM table1 WHERE link_id NOT IN (SELECT id FROM table2)";
I think that would do what you're asking for, if I understand you correctly. It may not be the fastest way to do it, though.

Although the selected answer works it is not efficient as the DB will need to do two seeks for the internal query and then again on the external query. The most efficient and effective query is a LEFT JOIN that removes the need for the second query.
SELECT b.* FROM names AS n LEFT JOIN blacklist_names AS b on n.id=b.id WHERE b.id IS NULL;
You can alias the tables like I did or not. I did it to make the code shorter.
What the query is doing is matching all ids found in both tables and then excluding them from the results by taking whats left from the "all names list" that is not in the blacklist.
EDIT: As per the author, putting the solution here to highlight it from the comments.
SELECT spotify.ID,spotify.land,spotify.song,spotify.link_id,spotify.pos1 FROM spotify LEFT JOIN spotify_blacklist ON (spotify.link_id = spotify_blacklist.URL) WHERE spotify_blacklist.URL IS NULL ORDER BY spotify.song ASC

Related

Using Select * in a SQL JOIN returns the wrong id value for the wrong table

I have two tables (PlayerDTO and ClubDTO) and am using a JOIN to fetch data as follows:
SELECT * FROM PlayerDTO AS pl
INNER JOIN ClubDTO AS cl
ON pl.currentClub = cl.id
WHERE cl.nation = 7
This returns the correct rows from PlayerDTO, but in every row the id column has been changed to the value of the currentClub column (eg instead of pl.id 3,456 | pl.currentClub 97, it has become pl.id 97 | pl.currentClub 97).
So I tried the query listing all the columns by name instead of Select *:
SELECT pl.id, pl.nationality, pl.currentClub, pl.status, pl.lastName FROM PlayerDTO AS pl
INNER JOIN ClubDTO AS cl
ON pl.currentClub = cl.id
WHERE cl.nation = 7
This works correctly and doesn’t change any values.
PlayerDTO has over 100 columns (I didn’t list them all above for brevity, but I included them all in the query) but obviously I don’t want to write every column name in every query.
So could somebody please explain why Select * changes the id value and what I need to do to make it work correctly? All my tables have a column called id, is that something to do with it?
SELECT *... is, according to the docs...
shorthand for “select all columns.” (Source: Dev.MySQL.com
Both your tables have id columns, so which should be returned? It's not indicated, so MySQL makes a guess. So select what you want to select...
SELECT pl.id, *otherfieldsyouwant* FROM PlayerDTO AS pl...
Or...
SELECT pl.* FROM PlayerDTO AS pl...
Typically, SELECT * is bad form. The odds you are using every field is astronomically low. And the more data you pull, the slower it is.

Issue with joins in a SQL query

SELECT
c.ConfigurationID AS RealflowID, c.companyname,
c.companyphone, c.ContactEmail, COUNT(k.caseid)
FROM
dbo.Configuration c
INNER JOIN
dbo.cases k ON k.SiteID = c.ConfigurationId
WHERE
EXISTS (SELECT * FROM dbo.RepairEstimates
WHERE caseid = k.caseid)
AND c.AccountStatus = 'Active'
AND c.domainid = 46
GROUP BY
c.configurationid,c.companyname, c.companyphone, c.ContactEmail
I have this query - I am using the configuration table to get the siteid of the cases in the cases table. And if the case exists in the repair estimates table pull the company details listed and get a count of how many cases are in the repair estimator table for that siteid.
I hope that is clear enough of a description.
But the issue here is the count is not correct with the data that is being pulled. Is there something I could do differently? Different join? Remove the exists add another join? I am not sure I have tried many different things.
Realized I was using the wrong table. The query was correct.

Joining SQL queries with where clause

I have 2 tables in a MYSQL database wich look like this:
Klant:
ID Naam Email Soort Status
6 test test test2
7 status test test test 20
8 soort test test test
9 soort test 2 test2 Museum
Mail:
ID Content Datum Titel
1 (lots of encoded HTML) 18-03-13 test
2 (lots of encoded HTML) 18-03-13 test2
4 (lots of encoded HTML) 18-03-13 alles weer testen
(yes, I'm still testing alot^^)
Now I have a SQL query that selects all from 'Klant' with a where clause which gets the ID from a previous page:
$strSQL = "SELECT * FROM Klant WHERE ID = '".$_GET["ID"]."' ";
What I want is to JOIN this query with the following query:
SELECT ID, Titel FROM Mail;
EDIT:
From all your answers and comments I think I begin to think my question maybe is totally wrong.. I'll explain where I need it for and I might not even need JOIN? I currently have a table wich includes the data from 'Klant' which looks like this:
The meaning is that I add another table which includes all the ID's and Title's from 'Mail'. I am sorry for the confusion I may have caused with you since I wasn't that clear with my question. I hope that this may clear up what I want and you guys can maybe tell me if I even need to JOIN this or can I do something else?
I am still a student and this is the first time I've had to use JOIN and I can't figure this out. If anyone can show me how to do this or push me in the right direction it would be great!
SELECT * FROM Klant t1
JOIN
SELECT ID, Titel FROM Mail t2
ON t1.ID = t2.ID
WHERE t1.Name = 'test'
To have the desired result do the following:
SELECT * FROM Klant t1
JOIN
SELECT ID, Titel FROM Mail t2
ON t1.ID = t2.ID
And if you want to have a specific row than just add the where clause:
WHERE t1.ID = 6
or
WHERE t1.Naam = 'test'
and so on
It is difficult to see how a JOIN is applicable in the example in your question.
A JOIN let's you pull information from more than one table based on a relationship. As far as I can see, your table's don't have any way to link a row in one with a row in the other, unless SteveP is correct and your id's provide that relationship.
For example, if your klant table had a mail_id column then you could do
SELECT *
FROM klant
JOIN mail ON klant.mail_id = mail.id
and this would return a row for every matching pair of rows in the two tables. Alternatively you could use a LEFT OUTER JOIN to pull back all rows from the table on the left of the JOIN and optionally data from a matching row on the right.
If there is nothing joining the table, you can use a CROSS JOIN which will return you a full cartesian of each row in table1 with every row in table2.
Something people often confuse with a JOIN is a UNION which allows you to write 2 SELECT statements and return the result set of both combined/joined together, but these should return the same columns in each query (e.g. selecting NULL in place of the column in a query if the query doesn't pull data for that column)
I'm guess that you want to join on the ID field which is common between the tables.
select * from Klant, Mail where Klant.ID = '".$_GET["ID"]."' and Klant.ID = Mail.ID
You can also do
select * from Klant
join Mail on Mail.ID = Klant.ID
where Klant.ID = '".$_GET["ID"]."'
You can do this directly by using the following query :
select k.ID,k.Naam, k.Email,k.Soort,k.Status, m.ID,m.Titel from Klant k, Mail m where k.ID = m.ID and k.ID = '".$_GET["ID"]."'

Selecting data from 2 different databases and comparing them

Forgive me if this question has already been asked, but... I'm trying to select data from 2 different tables in a database and count all the data in one table that is equal to the data in the second table if that makes sense? Below is the code I am trying to use
$select = "SELECT * FROM client_id, clientid, COUNT(client_id) FROM enquiry, check_s WHERE client_id = clientid";
Your query appears to be syntactically wrong.
What you can try is to join the two tables on a primary key(id?) and any other fields you're trying to match. The basic syntax would be like this:
SELECT * FROM
DB1.Table1
JOIN DB2.Table2
ON DB1.Table1.PrimaryKey = DB2.Table2.PrimaryKey;
If you're looking for an exact data match, you may have to join the tables based on all fields(in the ON clause in the above query).
Edit:
Now that you've explained it, you can try this:
SELECT table1.*, count(*) as `n` FROM table1
JOIN table2
ON table1.field = table2.field;
Again, if you need to compare more fields, just include them in the ON clause, and set conditions in the WHERE clause.
I think you might be looking for something like this:
Lets say your main table name is Client and your secondary table (from the form) is Enquiry and the column which you want to compare in client is called client_id and the same column in Enquiry is called clientid.
Then you have
Select Count(Client.*)
From Client, Enquiry
Where Client.client_id = Enquiry.clientid
Group by Client.client_id

Select rows that are different in SQL

I have a table with way too many columns and a couple million rows that I need to query for differences.
On these rows there will hopefully be only one column that is different and that should be the Auto incremented id field.
What I need to do is check to see if these rows ARE actually the same and if there are any that have any differences in any of the fields.
So for example, if the "Name" column is supposed to be "Peter, Paul and Mary" and the "Order #" column is supposed to be "132" I need to find any rows where those values aren't true, but I need to find it for every column in the table AND I don't actually know what the correct values are (meaning I can't just create a "SELECT...WHERE Name='This'" for each column).
So how can I find the rows that are different? (using straight SQL, no programming)
Would you think this answer is what you are looking for and would help you? here's a Link to find the appropriate sql query.
Let's suppose you coded a email newsletter signup form, but you forgot to double check that the email address was not a duplicate, or already in the database. We can write a query to find all the emails in our table that are duplicates, or occurs in more than one row.
The following SQL query works great for finding duplicate values in a table.
SELECT email,
COUNT(email) AS NumOccurrences
FROM users
GROUP BY email
HAVING ( COUNT(email) > 1 )
By using group by and then having a count greater than one, we find rows with with duplicate email addresses using the above SQL.
Blockquote
If you know the limit of the wrong results (say 10 for example) then you could order them and get only the first 11 results. You see where I am going with this, right?
I have no SQL expertise whatsoever though :)
Do you need to do this programmatically, or can you just run a few queries yourself to check it?
If the latter, I'd just do "select distinct name, order#" to start. This should return a list that includes "Peter Paul and Mary, 132" and possibly some other things.
Then find the other things by doing select ... where name = "this" as you suggest.
You could get even more info out of that first query by doing "select distinct name, order#, count(*) from ... group by name, order#". This would give you both the list of values and the frequency of a given set of values.
if I understand you correctly, (your question is not 100% clear to me), you are tryin g to find the rows that are unnecessary duplicates ? If so, Try these SQL queries:
Select A.Id, B.Id
From Table A
Join Table B
On A.Id <> B.Id
And A.ColA = B.ColA
And A.ColB = B.Col
And A.ColC = B.ColC
...
Or
Select ColA, ColB, etc.
From Table
Group By ColA, ColB, etc.
Having Count(*) > 1
If you have a correlation between two "independent" columns where there is really only one "correct" value for column B whenever column A is a given value, then you have a broken database design, because these correlation should have been factored out as a separate table.
Try this:
SELECT Name, OrderNum
FROM Orders T1
FULL OUTER JOIN (
SELECT Name, OrderNum
FROM Orders
GROUP BY Name, OrderNum
HAVING COUNT(*) > 1) T2
ON T1.Name = T2.Name
AND T1.OrderNum = T2.OrderNum
The nested select is identifying the duplicates, so you will need to target your common fields, the FULL OUTER JOIN excludes the duplicates from your result set. So essentially you are joining the table on itself to identify the duplicates and exclude them from your results. If you want only the duplicates then change the FULL OUTER JOIN to just JOIN.