How do I search multiple mySQL tables to find one specific row? - php

I have three tables: adapters, connectors, components
I need to be able to search them all to find a corresponding Part Number (part_num)
The part number is unique so I don't have to worry about multiple entries.
I use GET to find the part number in the URL, set it to $num, and then do the SELECT
What I've found is that I should use UNION, however the three tables have different columns and it gives me an error when trying to do the select. In the example below
Using UNION to find references from other tables
This is my code:
if(isset($_GET['num'])) {
$num = $_GET['num'];
$result = mysql_query("SELECT * FROM connectors WHERE part_num = '$num' UNION SELECT * FROM adapters WHERE part_num = '$num' UNION SELECT * FROM components WHERE part_num = '$num'"); }
Any help would be appreciated, so thanks in advance SO =)

You should probably have a fourth table Parts that identifies to which type table each part_num has been allocated. However, without that, you could still get what you're after with outer joins (wasteful though):
SELECT * FROM
connectors
LEFT JOIN adapters USING(part_num)
LEFT JOIN components USING(part_num)
WHERE
part_num = ?
Note that I have used ? as you really should be using prepared statements: if you don't know why, or what they are, read about Bobby Tables.

How about taking not all columns, but only titles or so on?
$sSql = "SELECT id, title, 1 FROM connectors WHERE part_num = '$num'
UNION
SELECT id, title, 2 FROM adapters WHERE part_num = '$num'
UNION
SELECT id, title, 3 FROM components WHERE part_num = '$num'";
You must adopt it to your table fields, but with this logic you will have an array where by the Third column (in my example), you can know if it is connector, adapter or component found, then generate proper links or do other actions with this data.
Another Way is to make Multi query, which will return multiple results by one database request. There are some ways to use it - using mysqli (http://lt.php.net/manual/en/mysqli.multi-query.php) or some of Adodb or PDO libraries.
Hope it will help.

To use UNION, the 3 recordsets must have the same number of columns, so you'll have to specifed which columns from each table that you want. From there, you'll have a single results set with the data from each of the 3 queries.

Related

MYSQL/PHP - Select all columns from table records distincting by one column

I'm a bit confused about DISTINCT keyword. Let's guess that this query will get all the records distincting the columns set in the query:
$query = "SELECT DISTINCT name FROM people";
Now, that query is fetching all the records distincting column "name" and at the same time only fetching "name" column. How I'm supposed to ONLY distinct one column and at the same time get all the desired columns?
This would be the scheme:
NEEDED COLUMNS
name
surname
age
DISTINCTING COLUMNS
name
What would be the correct sintaxis for that query? Thanks in advance.
If you want one row per name, then a normal method is an aggregation query:
select name, max(surname) as surname, max(age) as age
from t
group by name;
MySQL supports an extension of the group by, which allows you to write a query such as:
select t.*
from t
group by name;
I strongly recommend that you do not use this. It is non-standard and the values come from indeterminate matching rows. There is not even a guarantee that they come from the same row (although they typically do in practice).
Often, you want something like that biggest age. If so, you handle this differently:
select t.*
from t
where t.age = (select max(t2.age) from t t2 where t2.name = t.name);
Note: This doesn't use group by. And, it will return duplicates if there are multiple rows with the same age.
Another method uses variables -- another MySQL-specific feature. But, if you are still learning about select, you should probably wait to learn about variables.

How to get results from multiple tables using a single query in CodeIgniter?

I have a situation where i need to get data from 7 different tables for a particular processing to be performed.
I will need 7 simple SELECT all statements, nothing fancy. But to minimize the database hit, I will very much like to bundle these queries into 1 or 2 queries.
Like:
select * from table1; select * from table2; select * from table3;.
And will call this query from my code. Is is possible to get the results in something on the similar lines of .net's DataSet in PHP. I am looking for a solution in core PHP or CodeIgniter. I am using PDO for database connection.
PS: The tables have different schemas, no common point. So any solution with join or union will not work.
$results = $this->db-query("select * from tb1; select * from tb2");
now $result[0] should have all the records from tb1 and $results[1] should have the records from tb2.
Something on the similar line will be most helpful in this scenario.
Look into InnerJoin. That's how you make multiple selections at once - assuming you have a common data point
What you need is UNION
$this->db->query('SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2');
UNION ALL This is the UNION keyword, and the optional ALL keyword. UNION indicates that the results of the SELECT statement that precedes UNION will be combined with the results of the SELECT statement that follows UNION.
When you use the ALL keyword, duplicate rows are not removed from the combined set that is produced by the union. This can dramatically improve the performance of the query, because Access does not have to check the results for duplicate rows. You should use the ALL keyword if any of the following conditions is true:
You are certain that the select queries will not produce any
duplicate rows.
It does not matter if your results have duplicate rows.
You want to see duplicate rows.
EDITED
After your edition and what I've got it from your question then this might be helpful. You need to loop that queries to get an array of results as
$tablename = array('name1','name2','name3','name4','name5','name6','name7');
$results = array();
foreach($tablename as $key => $value){
$results[$key] = $this->db->query("select * from ".$value."")->result_array();
}
Multiple select query in codigniter
$this->db->select('t1.*, t2.*');
$this->db->from('table1 AS t1, table2 AS t2');
$query = $this->db->get();
$row = $query->result_array();
print_r($row);

how to properly use Mysql to SELECT * FROM table WHERE column='Any_value_in_Array'

Okay so I'm basically a noob when it comes to setting up tables and querying them ... but I think My title explains what I'm trying to do pretty well and I believe I'm looking for a way to use a JOIN but for the life of me can't figure out exactly how to do it (I've read some examples on S.O. and tutorials around the web but haven't been able to wrap my head around it). Basically I have a table called userFollowsSeries which has three columns
| userID | seriesID | series_title |
------------------------------------
| int | int | var_char |
and another table series that has a primary key seriesID and a bunch of relevant information about the series. Now I want to get all Information in table series for each seriesID for a user.
Now I'm basically trying to get each seriesID based on a single userID like this
$userFollows = mysqli_query($con, "SELECT * FROM userFollowsSeries WHERE userID='$user_id'") or die(mysql_error());
while($follows = mysqli_fetch_array($userFollows)){
$show_id=$follows['seriesID'];
echo $show_id; //this is realy just here for testing
$result = mysqli_query($con, "SELECT * FROM series WHERE id='$show_id'") or die(mysql_error());
while($row = mysqli_fetch_array($result)){
// i get and print out everything in a formatted for my html code
}
}
now I realize that this is less then ideal and is not very efficient but can't figure out how to do all of this in one statement/query using again i presume some sort of JOIN statement. Everything I have Works but is just really slow (presumably because of the query embeded in the while loop). Anyway's you can help me out with how a join or new table structure to improve this would be awesome and greatly appreciated.
Something along the lines of SELECT * FROM `series` WHERE `id` IN (SELECT `SeriesID` FROM `userFollowsSeries` WHERE `userID`=$user_id) should work nicely. Just be aware that it may not make good use of indexes. It may be better to select the IDs, build an array of them, then use IN with implode to join the array.
A JOIN basically glues two tables together on a column. Take this as an example:
SELECT * FROM userFollowsSeries INNER JOIN series ON (userFollowsSeries.seriesID = series.seriesID)
What we're doing here is, in effect, selecting everything from the userFollowsSeries, then for each record, attaching the row from the series table which satisfies the condition in the ON clause.
Your query should be
SELECT s.*
FROM userFollowsSeries ufs
INNER JOIN series s
ON s.id = ufs.seriesID
WHERE ufs.userID = {$user_id}
and you should make a foreign key or an index on field seriesID of table userFollowsSeries.

MySQL - selecting from multiple tables, possibly without joins?

It's been a while since I needed help, but today I'm here to basically get assistance from your knowledge. I'm currently quite stuck on a very annoying SQL problem, which is the following.
I have two tables. Painteditems, and specialitems. Both tables have unique column names (painteditemid, specialitemid etc), yet both tables share similar values. I want to get results from both tables.
Let's say this is my setup:
PaintedItems
paintedItemName
paintedItemColor
visible
SpecialItems
specialItemName
specialItemColor
visible
I used this query:
SELECT *
FROM `painteditems` AS pa,
`specialitems` AS sp
WHERE (pa.`visible` = 1
OR sp.`visible` = 1)
AND (pa.`painteditemname` = 'itemname1'
OR sp.`specialitemname` = 'itemname1')
AND (pa.`painteditemcolor` = 'black'
OR sp.`specialitemcolor` = 'black')
That resulted in:
Showing rows 0 - 29 ( 259,040 total, Query took 39.4352 sec)
even though both tables contain only 10.000 rows altogether. Adding this did nothing:
GROUP BY pa.`painteditemid`, sp.`specialitemid`
Still 260k rows. How should I approach this?
Thank you in advance.
edit: fixed spacing, code blocks
Sure sounds like you want a UNION between the two tables. Right now, you are getting a cartesian product which is why the results are so large:
select *, 'painted' Source
from painteditems
where visible = 1
and painteditemname = 'itemname1'
and painteditemcolor = 'black'
union all
select *, 'special' Source
from specialitems
where visible = 1
and specialitemname = 'itemname1'
and specialitemcolor = 'black'
You will need to replace the SELECT * with your column names. Also the number of columns and datatypes must match in both queries.
UNION ALL will return all rows from both tables, if you only want DISTINCT rows then you will want to use UNION
The UNION operator is used to combine the result-set of two or more SELECT statements. Defiantly You can make use of UNION as shown in the #bluefeet's answer If you meet below conditions.
SELECT statement within the UNION must have the same number of
columns
The columns must also have similar data type
The columns in each SELECT statement must be in the same order.
I would do this with a union all in the subquery:
select *
from ((select paintedItemName as ItemName, paintedItemColor as ItemColor, visible, 'Painted' as which
from painteditems
) union all
(select specialItemName, SpecialItemColor, visible, 'Special' as which
from specialitems
)
) t
where visible = 1 and itemname = 'itemname1' and itemcolor = 'black'
This allows you to have only one set of results. In a union, the column names come from the first subquery, which this renames to more generic names. The reason I prefer this approach is because the where clause does not need to be repeated multiple times -- which can lead to errors and maintenance problems.

select from multiple table with mysql

I had my query set up the other day as so
$query = "SELECT card_id,title,description,meta_description,seo_keywords,price
FROM cards,card_cheapest order by card_id";
As you can see, I was selecting card_id,title,description,meta_description,seo_keywords from the table cards, and price was coming from cheapest_card. They both have the card_id in common (in both tables). However, I ran into a bit of an issue. When I run the query in navicat lite, I receive an error "card_id is ambiguous". Was I doing something wrong?
When 2 or more tables have a column that is named the same, you have to qualify the table you want the column to be from.
i.e.:
$query = "SELECT cards.card_id,title,description,meta_description,seo_keywords,price
FROM cards,card_cheapest order by card_id";
Furthermore, do you really want to run the query this way, without a WHERE/JOIN-clause to define how to JOIN the two tables?
$query = "SELECT cards.card_id,title,description,meta_description,seo_keywords,price
FROM cards,card_cheapest WHERE cards.card_id = card_cheapest.card_id
ORDER BY card_id";
When you have the same column name in two tables you're selecting from, you have to prefix the part in the SELECT with one of the table names (it doesn't matter which if it's the same data)
such as SELECT cards.card_id, ...
EDIT: However, cularis's answer is much more explanatory than mine, and take note about joining the two card_id columns if you want to get correct results.
When you run queries that get information from multiple tables with shared field names you need to specify from which table you want to extract what field. You do this by specifying the table name before the field name.
In your case you have two options:
cards.card_id or card_cheapest.card_id.
Also I agree with #cularis, you are probably better of doing a join, but still you will need to specify which card_id you want to select: the one from cards or card_cheapest.

Categories