I am trying to fetch data from multiple tables depending on what is selected in a dropdown menu. My dropdown menu consists of a list of ID's (001, 002, etc).
Once a user selects one of them, I am using AJAX to dynamically fetch data depending on what was selected. I was able to fetch a single value depending on what was selected but having problems when multiple tables are involved.
My tables are set up like this:
Inventory table:
inven_ID (primary)
cost
description
Order table:
order_ID(primary)
orderdesc
Sale table:
inven_ID
order_ID
quantity
primary(inven_ID,order_ID)
My query is as follows:
$QRY = "SELECT
inven_ID,
order_ID,
cost,
description
FROM
Inventory,
Order,
Sale
WHERE Inventory.inven_ID = Sale.inven_id
AND Sale.order_ID = Order.order_ID
AND Order.order_ID ='".$q."'";
The $q represents the value from the dropdown menu (which I checked is valid). I am getting the error Column 'inven_ID' in field list is ambiguous. Basically, when they select some order id from the drop down (say 001), it looks for order_ID in my Order table, and fetches the inven_ID/cost/description of that particular order ID.
Eg. if someone ordered parts xy, yz, xyz for cost 10,20,30.
Selecting 001 would bring up:
001 xy 10
001 yz 20
001 xyz 30
I think I am not joining tables properly since the error says its ambiguous.
Any help on this?
edit: yes that fixed the problem, quite obvious that I did not catch it.
In the column list of your select, you just need to specify which inven_ID you want to retrieve. For instance:
SELECT Inventory.inven_ID, ...
The error is pretty obvious. inven_ID is ambiguous because you have it in Sale and in Inventory. Use a specifier like Sale.inven_ID or Inventory.inven_ID.
Related
I need to summary columns together on each row, like a leaderboard. How it looks:
Name | country | track 1 | track 2 | track 3 | Total
John ENG 32 56 24
Peter POL 45 43 35
Two issues here, I could use the
update 'table' set Total = track 1 + track 2 + track 3
BUT it's not always 3 tracks, anywhere from 3 to 20.
Secound if I don't SUM it in mysql I can not sort it when I present data in HTML/php.
Or is there some other smart way to build leaderboards?
You need to redesign your table to have colums for name, country, track number and data Then instead if having a wide table with just 3 track numbers you have a tall, thin table with each row being the data for a given name, country and track.
Then you can summarise using something like
SELECT
country,
name,
sum(data) as total
FROM trackdata
GROUP BY
name,
country
ORDER BY
sum(data) desc
Take a look here where I have made a SQL fiddle showing this working the way you want it
Depending upon your expected data however you might really be better having a separate table for Country, where each country name only appears once (and also for name maybe). For example, if John is always associated with ENG then you have a repeating group and its better to remove that association from the table above which is really about scores on a track not who is in what country and put that into its own table which is then joined to the track data.
A full solution might have the following tables
**Athlete**
athlete_id
athlete_name
(other data about athletes)
**Country**
country_id
country_name
(other data about countries)
**Track**
Track_id
Track_number
(other data about tracks)
**country_athlete** (this joining table allows for the one to many of one country having many athletes
country_athlete_id
country_id
athlete_id
**Times**
country_athlete_id <--- this identifies a given combination of athlete and country
track_id <--- this identifies the track
data <--- this is where you store the actual time
It can get more complex depending on your data, eg can the same track number appear in different countries? if so then you need another joining table to join one track number to many countries.
Alternatively, even with the poor design of my SQL fiddle example, it might be good to make name,country and track a primary key so that you can only ever have one 'data' value for a given combination of name, country and track. However, this decision, and that of normalising your table into multiple joined tables would be based upon the data you expect to get.
But either way as soon as you say 'I don't know how many tracks there will be' then you should start thinking 'each track's data appears in one ROW and not one COLUMN'.
Like others mentioned, you need to redesign your database. You need an One-To-Many relationship between your Leaderboard table and a new Tracks table. This means that one User can have many Tracks, with each track being represented by a record in the Tracks table.
These two databases should be connected by a foreign key, in this case it could be a user_id field.
The total field in the leaderboard table could be updated every time a new track is inserted or updated, or you could have a query similar to the one you wanted. Here is how such a query could look like:
UPDATE leaderboard SET total = (
SELECT SUM(track) FROM tracks WHERE user_id = leaderboard.user_id
)
I recommend you read about database relationships, here is a link:
https://code.tutsplus.com/articles/sql-for-beginners-part-3-database-relationships--net-8561
I still get a lot of issues with this... I don't think that the issue is the database though, I think it's more they way I pressent the date on the web.
I'm able to get all the data etc. The only thing is my is not filling up the right way.
What I do now is like: "SELECT * FROM `times` NATURAL JOIN `players`
Then <?php foreach... ?>
<tr>
<td> <?php echo $row[playerID];?> </td>
<td> <?php echo $row[Time];?> </td>
....
The thing is it's hard to get sorting, order and SUM all in ones with this static table solution.
I searched around for leaderboards and I really don't understand how they build theres with active order etc. like. https://www.pgatour.com/leaderboard.html
How do they build leaderboards like that? With sorting and everything.
Database schema
I have these three main tables:
products
groups
users
And these two pivot table:
product_user
group_user
Each user has a group.
Each product has a price which may be overriden by a price in the product_user pivot table or by a price in the group_user table.
Problem
Now I know how to join these tables and everything but with my current solution I am only able to select each of these prices to a separate column like price, user_price and group_price and prioritize them using PHP.
Question
Is it possible to select these 3 columns from these different tables and prioritize them into one column using only Sql?
So if there is a user-specific price selected this price into price, if not and there is a group-specific price selected this one and if there is no special price select the products default price.
Laravel specific solution
As #Shadow pointed out below, the solution is the MySQL coalesce function.
Using Laravel's query builder I was now able to achieve what I want using this statement:
$query->addSelect(
DB::raw('coalesce(product_user.price, group_product.price, products.price) as price')
);
Use the coalesce() function to return the 1st non-null value from its parameters.
select coalesce(product_user.price, group_user.price, product.price) as price
from ...
Since you have not shared the exact schema with me, I cannot provide mpre specific help. I assume that there are price columns in the tables.
I have a table full of products including price, name, date and ID (PK)
I am in need to update the records when there is a price change (Web scraping script), how would i go about this so that a new row is NOT inserted, rather the price and date are updated.....but the previous values need to remain in the DB....so that when i when i go
"SELECT * FROM items WHERE id ='27'";
Output wanted:
$400 12.4.2013
$314 22.4.2013
$250 12.4.2013
The product will be then displayed with all the updated values since the first price was downloaded, effectively it will be a history of the prices for the item...
the actual results i want to achieve would hopefully be
History for "Product 27" is:
To give more context, when i run my script... ./script.php update
all the new data should be inserted or updated....but old values remain
im not too sure how i should approach this....please provide me with some guidance or assistance
The best way to go about this while keeping a tidy database with easily maintainable and readable data would be to take what #KishorSubedi said in the comment and create a log table.
When you update your price in your Products Table, store the old price, along with its date and ID in the Log Table then when you need to look up all the records for that product you can JOIN the Log Table in your query.
Log Table
| ProductID | Price | Date |
| 27 | $300 | 02.1.2013 |
| 27 | $400 | 03.1.2013 |
This way you can have a nice and neat Products table that is not cluttered with multiples of the same product, and an unobtrusive log table that is easily accessible.
Hope this gives you some guidance on building your site and database.
If you want to keep the old values I would suggest saving them in a seperate table and to use the INSERT statement. You are always adding a new row, so you can not bypass an insert or select into or similar statement.
Table structure:
Items
------------------------------
Id primarykey
Name
Price
------------------------------
Id primarykey autoincrement
ItemId index
AddDate index
Price
Now when you scrape the web you will just insert the new price in the Price table. If you want to select all the prices for an item you can use
SELECT Items.Id
,Items.Name
,Price.Price
,Price.AddDate
FROM Items
LEFT JOIN Price
ON Items.Id=Price.ItemId
WHERE Items.Id='27'
ORDER BY Items.Name ASC, Price.AddDate ASC
And if you just want the latest or current price, you can use
SELECT Items.Id
,Items.Name
,P1.Price
,P1.AddDate
FROM Items
LEFT JOIN Price P1
ON Items.Id=Price.ItemId
LEFT JOIN Price P2
ON P1.ItemId=P2.ItemId
AND P1.Id<P2.Id
WHERE Items.Id='27'
AND P2.Id IS NULL
Add new column for history in 'item' table and each price change append the changed value to this column with a specific format as like date1:price1,date2:price2,....
I'm using this query to join data from two different tables. Invoice table holding data, with stock code and supplier code. Please check my query point out my error in query.
inv_code field holding stock code and supplier code. My second table is
cb_chart_temp having acc_code, and acc_name;
SELECT
`invoice`.`inv_code`,
`cb_chart_temp.acc_name`,
`invoice.sup_id`,
`cb_chart_temp`.`acc_name`
FROM
`invoice`,
`cb_chart_temp`
WHERE
inv_no LIKE 'PI%'
invoice.inv_code=cb_chart_temp.acc_code
AND invoice.sup_id=cb_chart_temp.acc_code
My result should look like this!
inv_code acc_name sup_id sup_name
ST-00001 Stock Name SUP-00001 Supplier Name
It misses an AND, as already pointed out by #Lion, plus it is doubtful that the join of keys is correct. As you have it, inv_code, acc_code, and sup_id all belong to the same domain, i.e., all of them are, e.g., invoice codes.
We have six categories Example :- a,b,c,d,e,f.
In each category we have products.
In a category i have 2 products & in b category i have 1 product.
I'm fetching this data from database.
product_id category_id
1 1
2 1
3 2
What should be best logic to display records, so two categories not display next to it.
Output product id like :- 1,3,2
I do not think such function exists. Even if you use DISTINCT it will only select the ones that do not duplicate and leave the out the rest, which is not what you need. So, I think I would run two queries at the same time, the first one will choose all the distinct queries, like 1,2,3,4 and after that, you can create a second query just to query normally all products. This way, let say.. if you had products by type like 1,1,2,3,3,3,4,4,4,4,5,5,5, then, the first sql query would list 1,2,3,4,5 and the second will just query normally, but still, your clients will see the distinct ones first.
SELECT DISTINCT type FROM table ORDER by id