get info from 2 tables at once? - php

I need to get info from 2 tables in one query, I searched for it on google and it came up with joins?
I got this code
mysql_query("SELECT code, url FROM apilinks, links WHERE apilinks.code='$code' and links.code='$code'");
but it doesn't seem to work, it outpus this mysql error
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/codyl/public_html/projects/tests/tirl/code.php on line 18
I need to have it find url and code, in both the links table and the apilinks table, because the url has a get variable, and 'apilinks' is setup differently than 'links'
so it will have the same looking url but it has to check both tables

I don't think your error is from your SQL query, but anyway:
Your SQL query generates a cartesian product. Every row in apilinks is joined with every row in links. This is rarely what you want. You need to add a JOIN condition to the WHERE clause.
From your query, I guess code is the column you want to join on.
SELECT links.code, url
FROM apilinks, links
WHERE apilinks.code=links.code
AND links.code='$code'
Or with using an explicit join, which may be more obvious to you:
SELECT links.code, url
FROM apilinks INNER JOIN links ON apilinks.code=links.code
WHERE links.code='$code'

I think you need to specify which code column you want:
SELECT links.code, links.url
FROM apilinks, links
WHERE apilinks.code='$code'
AND links.code='$code'

Another syntax:
mysql_query("SELECT a.code, l.url FROM apilinks a, links l WHERE a.code='$code' and l.code='$code'");
Note that I am assuming the url field is in the links table.

SELECT a.code, a.url
FROM apilinks a, links l
ON ( a.code = l.code )
WHERE a.code = "$code";

Related

SELECT statements have different number of columns

I am making a small php website in which you can follow others and then see their post.
I have three tables-
1.Posts, which has post_id and author_id
2.follow, which has following and follower
3.users, which has id, username, and all other stuff. I try the following in sql-
SELECT * FROM posts,follow,users WHERE posts.author_id=users.id AND users.id=follow.following AND follow.follower='$id' UNION SELECT * FROM posts,users WHERE posts.author_id=users.id AND users.id='$id'
Where $id is the id of the user logged in.
It displays the following error-
#1222 - The used SELECT statements have a different number of columns
I have searched for hours but I cannot find the answers to match with my query.
I will really appreciate an answer with a better version of the above code.
Thanks in advance.
Perhaps a JOIN would serve you better ... something like this:
SELECT * FROM posts
JOIN users on posts.author_id=users.id
JOIN followers on users.id=follow.following
WHERE follow.follower='$id'
When you union two queries together, the columns on both must match.
You select from posts,follow,users on the first query and posts,users on the second.
this won't work.
From the mysql manual:
The column names from the first SELECT statement are used as the column names for the results returned. Selected columns listed in corresponding positions of each SELECT statement should have the same data type

Query selected columns from two tables with a Condition clause

I have two tables-
1) ****Company_Form****
[Contract_No#,Software_Name,Company_Name,Vendor_Code]
2) ****User_Form****
[Contract_No,Invoice_No#,Invoice_Date,Invoice_Amount,Invoice_Submit_Date]
Fields denoted with # and bold are primary keys.
=>The user has to enter a software name for which he wants to get the data of.
=>I have to structure a query in which I have to display the result in the following form:
[Contract#,Software_Name,Company_Name,Invoice_No,Invoice_Date,Invoice_Submission_Date]
Now,
one Contract_No can contain many Invoice_no under its name in
the User Form table.
One Contract_No can occur one time only in
Company_Form table
The retrieved records have to be group by the latest Invoice_Date
I came to the logic that:
I have to first retrieve all the contract numbers with that software
name from Company_Form table.
I have to query that contract number from User_Form table and display
the data for each matched contract no. fetched from Company_Form
table.
The problem is that I am unable to structure a query in SQL that can do the task for me.
Kindly help me in formulating the query.
[PS] I am using SQL with PHP.
I tried a query like:
I tried one approach as :
SELECT a.ContractNo,a.SoftwareName,a.CompanyName,b.InvoiceNo,b.InvoiceDate,b.InvAmount,b.InvoiceSubmitDate
FROM Company_Form as a,User_Form as b
WHERE b.ContractNo IN(SELECT ContractNo FROM Company_Form WHERE
SoftwareName='$Sname') AND a.ContractNo=b.ContractNo;
But I am getting a error that sub query returns more than 1 row.
Can I get help from this?
I am assuming you are attempting to find the most recent price of the user selected software and its corresponding invoice. Here is an approach to do this. If this is tested to your satisfaction, I can add necessary explanation.
select uf.Contract_No#,
cf.Software_Name,
cf.Company_Name,
uf.Invoice_No#,
uf.Invoice_Date,
uf.Invoice_Amount,
uf.Invoice_Submit_Date
from User_Form uf
inner join (
-- Most recent sale of software
select Contract_No#, max(Invoice_Date)
from User_Form
group by Contract_No#
) latest
on (
-- Filter via join for latest match records
uf.Contract_No# = latest.Contract_No#
and uf.Invoice_Date = latest.Invoice_Date
)
inner join Company_Form cf
on cf.Contract_No# = uf.Contract_No#
where cf.Software_name = :software_name
If the requirement allows your sub query to return more than one row, I would suggest you to use IN instead of = in the where clause of your main query.
Please note that I have just looked at the query and have not fully understood the requirements.
Thanks.
I worked around for some time and finally came to the following query which works like a charm
SELECT a.ContractNo,a.SoftwareName,a.CompanyName,b.InvoiceNo,b.InvoiceDate,b.InvAmount,b.ISD
FROM Company_Form as a,User_Form as b
WHERE b.ContractNo IN (SELECT ContractNo FROM Company_Form WHERE SoftwareName='$Sname')
AND a.ContractNo=b.ContractNo;
If anybody needs help in understanding the logic of this query,feel free to comment below.

How to pull row from join when foreign key is null

I have a DB table with product information, and a DB table with tax rates.
My problem is that I am joining these two tables together, which works great.. until I disable "taxable" on a row for the product DB. Now my query is trying to join, but doesn't find a foreign key and I get no result at all.. I want to grab a result either way. I am using code igniter syntax, but it should be pretty obvious whats going on here:
$this->db->from('inventoryTaxRates a');
$this->db->join('inventory_items q', 'q.inventoryTaxRateID = a.inventoryTaxRateID');
sometimes q.inventyTaxRateID becomes 0, or disabled.. The query cannot join the two tables and gives me no result whatsoever. I want it to still give me the result from inventory_items.
I have tried left joining as well:
$this->db->join('inventory_items q', 'q.inventoryTaxRateID = a.inventoryTaxRateID', 'left');
You can specify a RIGHT join like this:
$this->db->join('inventory_items q',
'q.inventoryTaxRateID = a.inventoryTaxRateID',
'right');
You can use RIGHT JOIN, but I'd like to rewrite query like that:
SELECT .. FROM inventory_items ...
LEFT JOIN inventoryTaxRates ...

How can I get all field values from a query with JOINed tables?

I have this elementary query:
SELECT d.description, o.code FROM order_positions AS o
LEFT JOIN article_descriptions AS d ON (o.article_id = d.article_id)
WHERE o.order_id = 1
and I'm using MDB2 from PEAR to execute it and read the return values.
But somehow the result array always contains fields from the order_positions table only!, i.e. the result array looks like this
row[code] = 'abc123'
while I want it to look like this
row[description] = 'my description'
row[code] = 'abc123'
I already tried the following:
Vary the order of the fields, i.e. code first, then description.
Vary the order of the joined tables.
Used full table names instead of aliases.
Used the "MySQL join" instead (SELECT FROM table1, table2 WHERE table1.id = table2.id)
Used aliases with and without AS.
Some other facts:
Executing this query in MySQL Query Browser works fine, all fields are returned.
The order_positions table seems to be preferred, no matter what. When joining with additional tables I still only get fields from this table.
OK, I found the cause:
Fields with NULL values are not added to the array. In my test scenario description was in fact null and hence was not available in the array.
I'll still keep this (embarrassing) question, just in case someone else has this problem in the future.
Facepalm http://www.scienceblogs.de/frischer-wind/picard-facepalm-thumb-512x409.jpg
This should work:
SELECT d.description, o.code
FROM order_positions o, article_descriptions d
WHERE o.order_id = 1 AND d.article_id = o.article_id
Are you sure you're not using fetchOne() by mistake instead of fetchRow()?
Could you post your PHP code?
Another possibility is that in your code you missed the comma:
SELECT a b
is the same as
SELECT a AS b

Mysql Unique Query

I have a programme listing database with all the information needed for one programme packed into one table (I should have split programmes and episodes into their own) Now since there are multiple episodes for any given show I wish to display the main page with just the title names in ascending and chosen letter. Now I know how to do the basic query but this is all i know
SELECT DISTINCT title FROM programme_table WHERE title LIKE '$letter%'
I know that works i use it. But I am using a dynamic image loading that requires a series number to return that image full so how do I get the title to be distinct but also load the series number from that title?
I hope I have been clear.
Thanks for any help
Paul
You can substitute the DISTINCT keyword for a GROUP BY clause.
SELECT
title
, series_number
FROM
programme_table
WHERE title LIKE '$letter%'
GROUP BY
title
, series_number
There are currently two other valid options:
The option suggested by Mohammad is to use a HAVING clause in stead of the WHERE clause this is actually less optimal:
The WHERE clause is used to restrict records, and is also used by the query optimizer to determine which indexes and tables to use. HAVING is a "filter" on the final result set, and is applied after ORDER BY and GROUP BY, so MySQL cannot use it to optimize the query.
So HAVING is a lot less optimal and you should only use it when you cannot use 'WHERE' to get your results.
quosoo points out that the DISTINCT keyword is valid for all listed columns in the query. This is true, but generally people do not recommend it (there is no performance difference *In some specific cases there is a performance difference***)**. The MySQL optimizer however spits out the same query for both so there is no actual performance difference.
Update
Although MySQL does apply the same optimization to both queries, there is actually a difference: when DISTINCT is used in combination with a LIMIT clause, MySQL stops as soon as it finds enough unique rows. so
SELECT DISTINCT
title
, series_number
FROM
programme_table
WHERE
title LIKE '$letter%'
is actually the best option.
select title,series_number from programme_table group by title,series_number having title like '$letter%';
DISTINCT keyword works actually for a list of colums so if you just add the series to your query it should return a set of unique title, series combinations:
SELECT DISTINCT title, series FROM programme_table WHERE title LIKE '$letter%'
Hey thanks for that but i have about 1000 entries with the same series so it would single out the series as well rendering about 999 programmes useless and donot show.
I however found out away to make it unique and show the series number
SELECT * FROM four a INNER JOIN (SELECT title, MIN(series) AS MinPid FROM four WHERE title LIKE '$letter%' GROUP BY title) b ON a.title = b.title AND a.series = b.MinPid
Hopefully it helps anyone in the future and thank you for the replies :)

Categories